//
//  RequestGenerator.swift
//  Exchange
//
//  Created by rui on 2018/4/16.
//  Copyright © 2018年 common. All rights reserved.
//

import Foundation
import Alamofire

let kTimeOut: TimeInterval = 10

let kMessageEncryption = "app_2017"

let kMyBoundary = "myboundary"

let kID = "exchange_search_id"

class RequestGenerator {
    
    static func generateReuqest(_ serviceIdentifier: Service,httpMethod: HTTPMethodType,params: [String: Any],methodName: String,timeoutInterval:TimeInterval=kTimeOut) -> URLRequest {
        var mParams = params
        let server = ServerFactory.default.server(identifier: serviceIdentifier)
        var urlstr = server.baseurl + methodName;
//        if isUploadFile {
//            urlstr = server.uploadFileUrl + methodName
//        }
        
        if let id = mParams.removeValue(forKey: kID) {
            urlstr = urlstr + "/" + "\(id)"
        }
        if let count = server.apiVersion?.count, count > 0 {
            urlstr = server.baseurl + server.apiVersion! + "/" + methodName
        }
        let url = URL(string: urlstr)
        var request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: timeoutInterval)
        request.timeoutInterval = timeoutInterval
        if httpMethod == .upload {
            request.httpMethod = "POST"
            var data = Data()
            for obj in mParams {
                if let fileArr = obj.value as? [File]{
                    for file in fileArr {
                        data.append("--\(kMyBoundary)\r\n".data(using: .utf8)!)
                        let key = "Content-Disposition: form-data; name=\"\(obj.key)\"; filename=\"\(file.fileName)\"\r\n"
                        data.append(key.data(using: .utf8)!)
                        data.append("Content-Type: \(file.fileMIMEType)\r\n\r\n".data(using: .utf8)!)
                        data.append(file.fileData)
                        data.append("\r\n".data(using: .utf8)!)
                    }
                }else {
                    data.append("--\(kMyBoundary)\r\n".data(using: .utf8)!)
                    data.append("Content-Disposition:form-data;name=\"\(obj.key)\"\r\n".data(using: .utf8)!)
                    data.append("Content-Type:text/plain;charset=utf-8\r\n\r\n".data(using: .utf8)!)
                    data.append("\(obj.value)".data(using: .utf8)!)
                    data.append("\r\n".data(using: .utf8)!)
                }
            }
            data.append("--\(kMyBoundary)--\r\n".data(using: .utf8)!)
            request.httpBody = data
            request.setValue("multipart/form-data; boundary=\(kMyBoundary)", forHTTPHeaderField: "Content-Type")
            request.setValue("\(data.count)", forHTTPHeaderField: "Content-Length")
        }else {
            request.httpMethod = httpMethod.rawValue
                    
            if  httpMethod == .post || httpMethod == .put || httpMethod == .delete{
                ///加密签名处理
//                let appKey = server.privateKey
//                mParams.updateValue(appKey ?? "", forKey: "apiSecret")
//                let sign = RequestGenerator.signParams(mParams)
//                mParams.updateValue(sign, forKey: "sign")
//                let str = CryptoTool.aesEncrypt(content: mParams.jsonString ?? "")
//                request.setValue("application/json", forHTTPHeaderField: "Content-Type")
//                request.httpBody = str?.data(using: .utf8)
                do {
                    request = try JSONEncoding.default.encode(request, with: mParams)
                }catch {
                    dPrint("请求编码错误")
                }
            }else {
                do {
                    request = try URLEncoding.default.encode(request, with: mParams)
                }catch {
                    dPrint("请求编码错误")
                }
            }
            
        }
        if let token = AppInfo.default.token {
            request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        }
        
        let agent = SessionManager.defaultHTTPHeaders["User-Agent"]
        request.setValue(agent, forHTTPHeaderField: "User-Agent")
        return request
    }

    
    class func signParams(_ params:[String: Any]) -> String {
        let filterDict = params.filter {
            if $0.1 is String {
                return ($0.1 as! String).count > 0
            }
            return true
        }
        let sortDict = filterDict.sorted {  $0.0 < $1.0 }
        
        var sortStr = sortDict.reduce("", {
            return $0 + $1.0 + "=\($1.1)" + "&"
        })
        sortStr.removeLast()
        dPrint(sortStr)
        let md5 = sortStr.md5
        return md5
    }

}
